<template>
    <div v-loading="loading">
        <h2>{{ quizInfo?.title }}</h2>
        <el-form :model="searchForm" label-position="top" class="search-box">
            <el-form-item :label="$t('mod.quiz.report.search_box.label_1')">
                <el-select v-model="searchForm.is_answer">
                    <el-option :label="$t('mod.quiz.report.search_box.label_1_opt_1')" value="1"></el-option>
                    <el-option :label="$t('mod.quiz.report.search_box.label_1_opt_2')" value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item :label="$t('mod.quiz.report.search_box.label_2')">
                <el-switch v-model="searchForm.is_showHight" />
            </el-form-item>
            <div class="btn-list">
                <el-button color="#435764" @click="resetFilter">{{ $t('mod.quiz.report.search_box.btn_text_1') }}</el-button>
                <el-button color="#F06423" @click="getAnswerReportList">{{ $t('mod.quiz.report.search_box.btn_text_2') }}</el-button>
            </div>
        </el-form>
        <p class="search-res-num">{{ $t('mod.quiz.report.search_box.res', answerReportList.length) }}</p>
        <QuickFilter @filter-change="handleFilterChange" />
        <el-table stripe border :data="answerReportList" style="width: 100%">
            <el-table-column fixed sortable :label="$t('mod.quiz.report.table_label_1')" width="160">
                <template #default="{ row }">{{ row.last_name }} {{ row.first_name }}</template>
            </el-table-column>
            <el-table-column prop="code" :label="$t('mod.quiz.report.table_label_2')" width="200" />
            <el-table-column prop="status_text" :label="$t('mod.quiz.report.table_label_3')" width="120" />
            <el-table-column sortable :label="$t('mod.quiz.report.table_label_4')" width="280">
                <template #default="{ row }">{{ row.start_time ? formatLoginTime(row.start_time) : '' }}</template>
            </el-table-column>
            <el-table-column prop="duration_text" :label="$t('mod.quiz.report.table_label_5')" width="120" />
            <el-table-column prop="actual_score" :label="$t('mod.quiz.report.table_label_6')" width="80" />

            <!-- 新增动态问题列 -->
            <el-table-column v-for="(question, index) in questionColumns" :key="index" :label="question" align="center" width="200">
                <template #default="{ row }">
                    <span class="question-score" @click="openDialog(row.question_scores[index], row.id, index)" v-if="row.id">{{ row.question_scores[index].score || '0.00' }}</span>
                    <span v-else>{{ row.question_scores[index].score || '0.00' }}</span>
                </template>
            </el-table-column>
        </el-table>
        <div class="btn-list">
            <el-button color="#F06423" @click="downloadHandle">{{ $t('mod.quiz.report.btn_text_1') }}</el-button>
        </div>
    </div>

    <el-dialog v-model="dialogVisible" :title="`${singleInfo?.student_name} - ${singleInfo?.quiz_title}`" width="850" height="60vh" class="mobile-dialog">
        <div v-if="singleInfo">
            <el-descriptions :column="1" size="small" border>
                <el-descriptions-item :label="$t('mod.quiz.report.dialog.desc_1')">{{ singleInfo.student_name }}</el-descriptions-item>
                <el-descriptions-item :label="$t('mod.quiz.report.dialog.desc_2')">{{ singleInfo.quiz_title }}</el-descriptions-item>
                <el-descriptions-item :label="$t('mod.quiz.report.dialog.desc_3')">{{ singleInfo.question.question_point }}</el-descriptions-item>
                <el-descriptions-item :label="$t('mod.quiz.report.dialog.desc_4')" v-if="singleInfo">{{ formatLoginTime(singleInfo.end_time) }}</el-descriptions-item>
            </el-descriptions>

            <div class="quiz-item">
                <div class="quiz-info">
                    <h3>
                        {{ $t('mod.quiz.report.dialog.quiz_info.tit') }}<span class="qno">{{ singleInfo.question.index + 1 }}</span>
                    </h3>
                    <div class="state">{{ singleInfo.grade_answer.is_correct ? $t('mod.quiz.report.dialog.quiz_info.con_1') : $t('mod.quiz.report.dialog.quiz_info.con_2') }}</div>
                    <div class="grade">
                        {{ $t('mod.quiz.report.dialog.quiz_info.con_3') }}{{ singleInfo.grade_answer.score }} / {{ $t('mod.quiz.report.dialog.quiz_info.con_4')
                        }}{{ singleInfo.grade_answer.max_score }}
                    </div>
                </div>
                <div class="quiz-content">
                    <div class="question-answer-box">
                        <div class="q-text">{{ singleInfo.question.question_point }}</div>
                        <div class="q-text" v-html="singleInfo.question.question_detail"></div>
                        <el-radio-group disabled v-model="singleInfo.grade_answer.selected_option_ids[0]" v-if="singleInfo.question.question_type === 1">
                            <el-radio :value="answer.id" v-for="answer in singleInfo.question.answer" :key="answer.id">
                                <span class="opt-val">{{ answer.answer_text }}.</span>
                            </el-radio>
                        </el-radio-group>
                        <el-checkbox-group disabled v-model="singleInfo.grade_answer.selected_option_ids" v-else>
                            <el-checkbox :label="answer.answer_text" :value="answer.id" v-for="answer in singleInfo.question.answer" :key="answer.id" />
                        </el-checkbox-group>
                    </div>
                    <div class="question-feedback-box">
                        <div class="specific-feedback">
                            {{ singleInfo.grade_answer.is_correct ? $t('mod.quiz.report.dialog.quiz_content.specific_feedback_1') : $t('mod.quiz.report.dialog.quiz_content.specific_feedback_2') }}
                        </div>
                        <div class="right-answer">
                            {{ $t('mod.quiz.report.dialog.quiz_content.right') }}
                            <p v-for="correct in singleInfo.question.answer.filter(e => singleInfo?.grade_answer.correct_option_ids.includes(e.id))" :key="correct.id">
                                {{ correct.answer_text }}
                            </p>
                        </div>
                    </div>
                    <div class="feedback-box" v-if="isView">
                        {{ $t('mod.quiz.report.dialog.quiz_content.feedback') }}
                        <div class="rich-box" v-html="singleInfo.grade_answer.comment"></div>
                        <el-button color="#F06423" @click="isView = false">{{ $t('mod.quiz.report.dialog.quiz_content.feedback_btn_text') }}</el-button>
                    </div>
                    <div class="feedback-box" v-else>
                        <el-form label-position="top">
                            <el-form-item :label="$t('mod.quiz.report.dialog.quiz_content.form.label_1')" size="large">
                                <RichTextEditor v-model="singleInfo.grade_answer.comment" @update-richValue="singleInfo.grade_answer.comment = $event" />
                            </el-form-item>
                            <el-form-item :label="$t('mod.quiz.report.dialog.quiz_content.form.label_2')" size="large">
                                <el-input v-model="singleInfo.grade_answer.score">
                                    <template #append>{{ $t('mod.quiz.report.dialog.quiz_content.form.label_2_tip') }} {{ singleInfo.grade_answer.max_score }}</template>
                                </el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button color="#435764" @click="isView = true" :loading="dialogLoading">{{ $t('golbal.btn_text_3') }}</el-button>
                                <el-button @click="saveHandle" color="#F06423" :loading="dialogLoading">{{ $t('golbal.btn_text_1') }}</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </div>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false" color="#435764" :loading="dialogLoading">{{ $t('golbal.btn_text_5') }}</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'

import QuickFilter from '@/components/QuickFilter.vue'
import RichTextEditor from '@/components/RichTextEditor.vue'

import QuizService from '@/api/quiz'
import QuestionService from '@/api/question'
import type { AnswerReportItem, QuizInfo, SingleItem } from '@/types/quiz'

import { downloadCSV, formatLoginTime } from '@/utils/global'

import { useI18n } from 'vue-i18n'
import type { SupportedLocales } from '@/locales/i18n'
import type { MessageSchema } from '@/types/i18n'

interface FilterParams {
    lastName: string
    firstName: string
}

const route = useRoute()
const quizId = computed(() => Number(route.params.quizId)) // quiz id
const loading = ref(false)
const { t } = useI18n<{ message: MessageSchema }, SupportedLocales>()

// 搜索
const searchForm = reactive({
    is_answer: '1',
    is_showHight: false,
})
const resetFilter = () => {
    searchForm.is_answer = '1'
    searchForm.is_showHight = false
    filters.value = {
        lastName: 'all',
        firstName: 'all',
    }
    getAnswerReportList()
}
// 姓氏和名字 筛选
const filters = ref<FilterParams>({
    lastName: 'all',
    firstName: 'all',
})
const handleFilterChange = (newFilters: FilterParams) => {
    filters.value = newFilters
    getAnswerReportList()
}

// 答题报告
const answerReportList = ref<AnswerReportItem[]>([])
const checkedReportId = ref<number>()
const questionColumns = computed(() => {
    if (!answerReportList.value[0]) return []
    return answerReportList.value[0].question_scores.map((item, index) => `Q: ${index + 1}`)
})
function getAnswerReportList() {
    loading.value = true
    const form = {
        ...searchForm,
        additional_last_name: filters.value.lastName,
        additional_first_name: filters.value.firstName,
    }
    QuizService.recordsToTeacher(quizId.value, form)
        .then(res => {
            if (res.items.length) {
                const items = res.items
                // 添加总平均
                items.push({
                    id: 0,
                    student_id: 0,
                    first_name: t('mod.quiz.report.table_label_1_col'),
                    last_name: '',
                    additional_first_name: '',
                    additional_last_name: '',
                    code: '',
                    email: '',
                    status: 0,
                    status_text: '',
                    start_time: '',
                    end_time: null,
                    duration: 0,
                    duration_text: '',
                    total_score: '',
                    actual_score: res.average_scores.overall.average,
                    question_scores: res.average_scores.questions.map((item: any) => ({
                        is_correct: true,
                        max_score: 0,
                        score: item.average_score,
                        question_id: 0,
                    })),
                })
                answerReportList.value = items
            } else {
                answerReportList.value = []
            }
        })
        .finally(() => {
            loading.value = false
        })
}

// 单题详情弹窗
const dialogVisible = ref(false)
const isView = ref(true) // 审查模式/改分模式
const singleInfo = ref<SingleItem>()
const dialogLoading = ref(false)
const openDialog = (question: any, id: number, index: number) => {
    dialogLoading.value = true

    QuestionService.questionByIdAndRecordId(id, question.question_id)
        .then(res => {
            singleInfo.value = res
            singleInfo.value.question.index = index
            dialogVisible.value = true
            checkedReportId.value = id
        })
        .finally(() => {
            dialogLoading.value = false
        })
}
const saveHandle = () => {
    if (!singleInfo.value) return
    if (!checkedReportId.value) return

    dialogLoading.value = true
    QuizService.editScore(checkedReportId.value, singleInfo.value.question.id, {
        score: singleInfo.value.grade_answer.score,
        comment: singleInfo.value.grade_answer.comment,
    })
        .then(() => {
            isView.value = true
            dialogVisible.value = false
            getAnswerReportList()
        })
        .finally(() => {
            dialogLoading.value = false
        })
}

// 下载
const downloadHandle = () => {
    const form = {
        ...searchForm,
        additional_last_name: filters.value.lastName,
        additional_first_name: filters.value.firstName,
    }
    QuizService.exportCSV(quizId.value, form).then(res => {
        downloadCSV(res, t('mod.quiz.report.btn_text_1_tip', quizInfo.value?.title || ''))
    })
}

const quizInfo = ref<QuizInfo>()
function getQuizInfo() {
    QuizService.getById(quizId.value).then(res => {
        quizInfo.value = res
    })
}

onMounted(() => {
    getAnswerReportList()
    getQuizInfo()
})
</script>

<style lang="less" scoped>
.quiz-item {
    margin-top: 30px;
    display: flex;
    align-items: flex-start;
    gap: 18px;

    .quiz-info {
        margin-bottom: 28px;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15);
        border-radius: 2px;
        padding: 8px;
        background-color: #f9f9f9;
        width: 128px;
        font-size: 12px;
        color: #4c4c4c;
        line-height: 1.6;
        flex-shrink: 0;

        h3 {
            border-radius: 2px;
            padding: 2px 6px;
            color: #fff;
            background-color: #f06423;
            line-height: 1;

            .qno {
                font-size: 20px;
            }
        }

        .state,
        .grade {
            margin-top: 8px;
        }

        :deep(.quiz-mark) {
            margin-top: 8px;
            padding: 0;
            color: #4c4c4c;
            font-size: 12px;
            line-height: 20px;

            & > span {
                display: flex;
                align-items: center;
                gap: 4px;
            }
        }
    }

    .quiz-content {
        flex-grow: 1;

        .question-answer-box {
            border-radius: 4px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15);
            padding: 12px;
            background-color: #f9f9f9;
            width: 100%;

            :deep(.q-text) {
                font-size: 15px;
                color: #4c4c4c;
                line-height: 1.6;

                p,
                li {
                    margin-bottom: 8px;
                }
            }

            .el-radio-group {
                margin-top: 22px;
                padding-left: 8px;
                width: 100%;

                :deep(.el-radio) {
                    margin-top: 8px;
                    font-size: 15px;
                    color: #4c4c4c;
                    line-height: 1.6;
                    height: auto;
                    width: 100%;
                    align-items: flex-start;

                    .el-radio__input {
                        margin-top: 6px;
                    }

                    .el-radio__label {
                        font-weight: 400;
                        white-space: wrap;

                        display: flex;
                        align-items: flex-start;
                        gap: 10px;
                    }

                    .el-radio__input.is-checked + .el-radio__label {
                        color: #4c4c4c;
                    }
                }
            }

            .el-checkbox-group {
                margin-top: 22px;
                padding-left: 8px;
                width: 100%;

                :deep(.el-checkbox) {
                    margin-top: 14px;
                    font-size: 15px;
                    color: #4c4c4c;
                    line-height: 1.6;
                    height: auto;
                    width: 100%;
                    align-items: flex-start;

                    .el-checkbox__label {
                        font-weight: 400;
                        white-space: wrap;

                        display: flex;
                        align-items: flex-start;
                        gap: 10px;
                    }

                    .el-checkbox__input.is-checked + .el-checkbox__label {
                        color: #4c4c4c;
                    }
                }
            }

            .remove-answer {
                margin-top: 28px;
                color: #4c4c4c;

                &:hover {
                    color: #f06423;
                }
            }
        }

        .question-feedback-box {
            margin-top: 15px;
            border-radius: 4px;
            border: 1px solid #ffeeba;
            padding: 12px 18px;
            background-color: #fff3cd;
            color: #977204;
            font-size: 15px;
            line-height: 1.6;

            .specific-feedback {
                margin-bottom: 8px;
            }
        }

        .feedback-box {
            margin: 15px 0 50px 0;
            border-radius: 4px;
            border-color: 1px solid #c3e6cb;
            padding: 12px 18px;
            background-color: #d4edda;
            color: #977204;
            font-size: 15px;
            line-height: 1.6;

            .rich-box {
                margin-bottom: 15px;
            }

            :deep(.ck-editor) {
                width: 100%;

                .ck-editor__main {
                    .ck-content {
                        height: 200px;
                        overflow-y: auto;
                    }
                }
            }
        }
    }
}

h2 {
    margin-bottom: 30px;
    font-size: 30px;
    font-weight: normal;
    line-height: 1.2;
    color: #000;
}

.search-box {
    border: 1px solid #dee2e6;
    border-radius: 4px;
    padding: 15px;
    background-color: #f8f9fa;

    .el-form-item {
        width: 50%;
    }

    .btn-list {
        margin-top: 0;
        justify-content: flex-end;
    }
}

.search-res-num {
    margin-top: 8px;
    margin-bottom: 15px;
    color: #4c4c4c;
    font-size: 15px;
}

.question-score {
    cursor: pointer;
}

.btn-list {
    margin-top: 30px;
    display: flex;
    justify-content: center;
    width: 100%;
}
</style>
